package worker

import (
	"context"
	"time"

	"gitee.com/yutiandou/wdtools/wdsys"

	"gitee.com/yutiandou/wdRPC/server/config"
	"gitee.com/yutiandou/wdRPC/server/connpool"
)

type Workers struct {
	BlockPipe chan *connpool.Msg
	MsgQueue  chan *connpool.Msg
	handler   func(*connpool.Msg)
	gameover  context.CancelFunc
}

func NewWorkers(call func(*connpool.Msg)) (workers *Workers) {
	workers = &Workers{
		BlockPipe: make(chan *connpool.Msg, config.Conf.MaxQueueLength),
		MsgQueue:  make(chan *connpool.Msg, config.Conf.MaxQueueLength),
		handler:   call,
	}
	ctx, gmov := context.WithCancel(context.Background())
	workers.gameover = gmov
	_, count := wdsys.GetCpuPercent()
	for i := 0; i < count; i++ {
		go func(cont context.Context) {
			for {
				select {
				case <-cont.Done():
					break
				case msg := <-workers.BlockPipe:
					call(msg)
				default:
					select {
					case msg := <-workers.BlockPipe:
						call(msg)
					case msg := <-workers.MsgQueue:
						call(msg)
					}
				}
			}
		}(ctx)
	}
	return
}

func (w *Workers) OffDuty() {
	close(w.BlockPipe)
	close(w.MsgQueue)
	for {
		if (len(w.BlockPipe) == 0) && (len(w.MsgQueue) == 0) {
			w.gameover()
			break
		}
		<-time.After(time.Second * 3)
	}
}
